(function (factory) {
  // Establish the root object, `window` (`self`) in the browser, or `global` on the server.
  // We use `self` instead of `window` for `WebWorker` support.
  var root =
    (typeof self == "object" && self.self === self && self) ||
    (typeof global == "object" && global.global === global && global);

  root.route = factory(
    root,
    root.Route,
    root.utils,
    root._,
    root.jQuery || root.Zepto || root.ender || root.$
  );
})(function (root, Route, utils, _, $) {
  return {
    init: function (routes, obj) {
      var currentController = null;

      //用于把字符串转化为一个函数，是路由的处理核心
      var routeHandler = function (key, routeUrl) {
        var goPage = function (pageName, flag) {
          $.ajax({
            url: pageName,
            async: false,
            success: function (v) {
              $page = $(v);
              $("#app").html("").append($page);
              /*							$page.filter('script[type="text/javascript"]').each(function(){
								$.globalEval(this.text || this.textContent || this.innerHTML || '');
							});*/
              if (pageName.indexOf("index.html") > 0) {
                var scriptName = pageName.replace(".html", ".js");
                $.getScript(scriptName);
              }
            },
            error: function () {
              notfound(myPage);
            },
          });
        };

        return function () {
          goPage(routeUrl);
          obj.trigger("routeChange", key);
        };
      };

      for (var key in routes) {
        routes[key] = routeHandler(key, routes[key]);
      }

      var router = Router(routes).configure({
        notfound: function () {
          console.log("notfound");
          window.location.hash = "#/";
        },
      });
      router.init();
    },
  };
});
